function inarray(_cid, _phase, _array)
{
    var found = false;

    if (_array == null)
      return false;

    $.each(_array, function(index, element)
    {
        if ((element.phase == _phase.toString()) && (element.c_id == _cid.toString()))
        {
            found = true;
            return false;       // break;
        }
    })

    return found;
    
}

function setup_pic(_cid, _phase)
{
    var seed = Math.floor(Math.random() * (1000 - 1 + 1)) + 1;
    $('img[name=preview]').attr('src', 'req/pic_list.php?oper=disp&cid='+_cid+'&phase='+_phase+'&'+seed);
}

function gettd(_i, _j, _fill)
{
    var classes = new Array();
    var span = '';

    try
    { 
        if ((sel_cont == i) && (sel_phase == j))
        {
            classes.push('selected');
        }
    }
    catch (e)
    {
    }

    if (inarray(_i,_j,_fill))
    {
        classes.push('loaded');
        text = 'Есть';
    }
    else
    {
        text = 'Нет';
    }

    return '<td ident="' + _i + '-' + _j + '" class="' + classes.join(' ')+'">'+text+'</td>'
}

function render_table()
{
    var fill = new Array();
    var cont_list = new Array();

    $.ajaxSetup({async: false});

    $.getJSON('req/pic_list.php?oper=list', function (data)
        {
            fill = data;
        });


    $.getJSON('req/con_opt.php', function (data)
        {
            cont_list = data;
        });

    var phase_name = ["ЖМ", "Фаза 1","Фаза 2","Фаза 3","Фаза 4","Фаза 5","Фаза 6","Фаза 7","Фаза 8", "ОС" ];

    var out = '<table id="con-tab"><tr><th id="top" class="ui-th-column ui-state-default">№</br>контр</th><th id="top" class="ui-th-column ui-state-default">Название СО</th>';

    for (phase in phase_name)
    {
        out += '<th id="top" class="ui-th-column ui-state-default">' + phase_name[phase] + '</th>';
    }

    out += '</tr>';

    for(cont in cont_list)
    {
 
        out += '<th id="left-id" class="ui-th-column ui-state-default">'+cont_list[cont].id+'</th>'+'<th id="left-location" class="ui-th-column ui-state-default">'+((cont_list[cont].location == null)?'':cont_list[cont].location)+'</th>';

        for (j=0; j <= 9; j++)   
        {
            out += gettd(cont_list[cont].id,j,fill);
        }

        out += '</tr>';
    }

    return out;
}

function setup_cell()
{
    var pp = $('#con-tab td.selected').attr('ident').split('-');
    setup_pic(pp[0], pp[1]);

    $("#upload-button").button({disabled: false});
        
    if ($('#con-tab td.selected').hasClass('loaded'))
    {
        $("#remove-button").button({disabled: false});
    }
    else
    {
        $("#remove-button").button({disabled: true});
    }
}

$(function() { 

    $('#content-plan').html(render_table());

    $('#con-tab td').click(function()
    {
        $('#con-tab td.selected').removeClass('selected');
        $(this).addClass('selected');

        var pp = $(this).attr('ident').split('-');

        setup_pic(pp[0], pp[1]);

        $("#upload-button").button({disabled: false});

        if ($(this).hasClass('loaded'))
        {
            $("#remove-button").button({disabled: false});
        }
        else
        {
            $("#remove-button").button({disabled: true});
        }

    });

    $("#upload-button").button({ disabled: true }).click(function ()
    {
        try 
        {
            var pp = $('#con-tab td.selected').attr('ident').split('-');
            $("#upload-form input[name=cont]").val(pp[0]);
            $("#upload-form input[name=phase]").val(pp[1]);
            $("#upload-form input[name=scrollpos]").val($('#content-plan').scrollLeft()+","+$('#content-plan').scrollTop());

            $("#upload-form").dialog("open");
        }
        catch(e)
        {
            alert("Error:"+e.message);
        }
    });

    $("#remove-button").button({ disabled: true }).click(function ()
    {
        try
        {
            var pp = $('#con-tab td.selected').attr('ident').split('-');

            if (confirm("Удалить изображение для фазы: "+pp[1]+" контроллера: "+pp[0]+"?"))
            {
                    $.getJSON('req/pic_list.php?oper=del&cid=' + pp[0] + '&phase=' + pp[1], function (data)
                    {
                        $('#con-tab td.selected').html("Нет");
                        $('#con-tab td.selected').removeClass('loaded');
                        $("#remove-button").button({disabled: true});

                        setup_pic(pp[0], pp[1]);

                    });
            }
        }
        catch(e)
        {
            alert("Error:"+e.message);
        }
    });

    $("#upload-form").dialog(
    {
        autoOpen: false,
        height: 'auto',
        width: 'auto',
        modal: true,
        resizable: false,

        buttons: {
            "Загрузить": function ()
            {
                
                var bValid = true;

                $('#post-form').submit();

            },
            "Отменить": function ()
            {
                $(this).dialog("close");
            }
        }
    });

    if ((typeof(sel_cont) != 'undefined') && (typeof(sel_phase) != 'undefined'))
    {

        $('#con-tab td[ident='+sel_cont+'-'+sel_phase+']').addClass('selected');
        setup_cell();
    }
    else
    {   
        $('#con-tab tr:nth-child(2) td:first').addClass('selected');
        setup_cell();
    }

    if (typeof(scrollpos) != 'undefined')
    {
        var pp = scrollpos.split(',');

        $('#content-plan').scrollLeft(pp[0]);
        $('#content-plan').scrollTop(pp[1]);
    }

});
